<?php

/**
 * 
 * 
 * @todo Permettre dans value un set du type : SET x = x + 1
 * @author Sokaru
 *
 */
class Mac_Db_Query_Update extends Mac_Db_Query_Abstract
{
    private $table = null;
    
    private $values = array();
    
    private $whereClause = array();
    
    private $order = null;
    
    private $limit = null;
    
    private function __construct ($table)
    {
        $this->table = $table;
    }
    
    /**
     * Initialize the query
     */
    public static function table ($table)
    {
        return new self($table);
    }
    
    public function value ($field, $value)
    {
        $this->values[$field] = Mac_Db_Helper::prepareValue($value);
        return $this;
    }
    
    public function rawValue ($field, $value)
    {
        $this->values[$field] = $value;
        return $this;
    }
    
    public function where (Mac_Db_Clause_Where $where)
    {
        $this->whereClause = array($where->__toString());
        return $this;
    }
    
    public function orWhere (Mac_Db_Clause_Where $where)
    {
        $this->whereClause[] = $where->__toString();
        return $this;
    }
    
    public function orderBy ($order)
    {
        $this->order = $order;
        return $this;
    }
    
    public function limit ($limit)
    {
        $this->limit = $limit;
        return $this;
    }
    
    public function __toString ()
    {
        $req = 'UPDATE '.$this->table.' SET ';
        
        $sets = $this->values;
        array_walk($sets, function(&$value, $index) { $value = $index.'='.$value; });
        $req .= implode(', ', $sets);
        
        if (!empty($this->whereClause)) {
            $req .= " WHERE ".Mac_Db_Helper::outputWhere($this->whereClause);
        }
        
        if (isset($this->order)) {
            $req .= " ORDER BY ".Mac_Db_Helper::outputOrderBy($this->order);
        }
        
        if ($this->limit !== null) {
            $req .= ' LIMIT '.$this->limit;
        }
        
        return $req;
    }
}